<template>
  <div class="inventory-distribution">
        <!-- 产品信息栏 -->
    <div class="product-info-bar">
      <div class="product-item">
        <span class="product-name">{{ productInfo.itemName }} {{ productInfo.itemId }}</span>
      </div>
      <div class="product-item">
        <span class="label">货品类型</span>
        <span class="value">{{ productInfo.itemType || '饮品类' }}</span>
      </div>
      <div class="product-item">
        <span class="label">规格型号</span>
        <span class="value">{{ productInfo.itemSpec || '20*50*60' }}</span>
      </div>
      <div class="product-item">
        <span class="label">单位</span>
        <span class="value">{{ productInfo.unitName || '瓶' }}</span>
      </div>
      </div>

    <!-- 库存统计卡片 -->
      <div class="statistics-cards">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
              <div class="stat-number blue">{{ statistics.currentQty }}</div>
              <div class="stat-label">当前库存</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
              <div class="stat-number blue">{{ statistics.availableQty }}</div>
              <div class="stat-label">可用库存</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
              <div class="stat-number orange">{{ statistics.toOutQty }}</div>
              <div class="stat-label">待出库</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
              <div class="stat-number orange">{{ statistics.toInQty }}</div>
              <div class="stat-label">待入库</div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 库存明细表格 -->
      <el-card class="table-card">
        <template #header>
          <div class="table-header">
            <div class="table-title">库存明细</div>
            <div class="table-actions">
              <el-button type="primary" @click="exportData">导出</el-button>
              <el-button @click="refreshData">刷新</el-button>
            </div>
          </div>
        </template>
        

        

        
              <el-table 
          :data="inventoryList" 
          border 
          style="width: 100%" 
          v-loading="loading"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="serialNo" label="序号" width="60" />
          <el-table-column prop="warehouseName" label="仓库名称" width="120" />
          <el-table-column prop="locationName" label="仓位名称" width="120" />
          <el-table-column prop="currentInventory" label="当前库存" width="100">
            <template #default="scope">
              {{ scope.row.currentInventory || 0 }}
            </template>
          </el-table-column>
          <el-table-column prop="availableInventory" label="可用库存" width="100">
            <template #default="scope">
              {{ scope.row.availableInventory || 0 }}
            </template>
          </el-table-column>
          <el-table-column prop="pendingInbound" label="待入库" width="100">
            <template #default="scope">
              {{ scope.row.pendingInbound || 0 }}
            </template>
          </el-table-column>
          <el-table-column prop="pendingOutbound" label="待出库" width="100">
            <template #default="scope">
              {{ scope.row.pendingOutbound || 0 }}
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const route = useRoute()

// 响应式数据
const loading = ref(false)
const selectedRows = ref<any[]>([])

// 产品信息
const productInfo = reactive({
  itemId: '',
  itemName: '',
  itemType: '',
  itemSpec: '',
  unitName: ''
})

// 统计数据
const statistics = reactive({
  currentQty: 0,
  availableQty: 0,
  toOutQty: 0,
  toInQty: 0
})

// 分页数据（如需分页可扩展）
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const inventoryList = ref<any[]>([])

// 获取货品详情
const fetchGoodsDetail = async () => {
  if (!productInfo.itemId) return;
  try {
    const { data } = await axios.get(`/api/app/goods-management/${productInfo.itemId}/goods-by-id`)
    if (data?.data) {
      Object.assign(productInfo, {
        itemName: data.data.itemName,
        itemType: data.data.itemTypeName,
        itemSpec: data.data.itemSpec,
        unitName: data.data.unitName
      })
    }
  } catch (error) {
    ElMessage.error('获取货品详情失败')
    console.error('获取货品详情失败:', error)
  }
}

// 生成假数据
const generateMockInventoryData = () => {
  const mockInventoryDetails: any[] = []
  const warehouses = [
    { name: '零件仓库', locations: ['库位一', '库位二', '库位三'] },
    { name: '颜料仓库', locations: ['库位一', '库位二'] },
    { name: '后勤仓库', locations: ['库位一', '库位二', '库位三', '库位四'] },
    { name: '机械仓库', locations: ['库位一', '库位二'] },
    { name: '食品仓库', locations: ['库位一', '库位二', '库位三'] }
  ]
  
  let serialNo = 1
  warehouses.forEach(warehouse => {
    warehouse.locations.forEach(location => {
      mockInventoryDetails.push({
        serialNo: serialNo++,
        warehouseName: warehouse.name,
        locationName: location,
        currentInventory: Math.floor(Math.random() * 500) + 100,
        availableInventory: Math.floor(Math.random() * 200) + 50,
        pendingInbound: Math.floor(Math.random() * 30) + 5,
        pendingOutbound: Math.floor(Math.random() * 30) + 5
      })
    })
  })
  
  return mockInventoryDetails
}

// 获取库存分布明细
const fetchInventoryDistribution = async () => {
  loading.value = true
  try {
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 300))
    
    // 生成假数据
    const mockInventoryDetails = generateMockInventoryData()
    
    // 更新产品信息
    if (!productInfo.itemName) {
      productInfo.itemName = '可口可乐'
      productInfo.itemType = '饮料'
      productInfo.itemSpec = '200ml'
      productInfo.unitName = '瓶'
    }
    
    // 计算统计数据
    const totalCurrent = mockInventoryDetails.reduce((sum, item) => sum + item.currentInventory, 0)
    const totalAvailable = mockInventoryDetails.reduce((sum, item) => sum + item.availableInventory, 0)
    const totalPendingIn = mockInventoryDetails.reduce((sum, item) => sum + item.pendingInbound, 0)
    const totalPendingOut = mockInventoryDetails.reduce((sum, item) => sum + item.pendingOutbound, 0)
    
    statistics.currentQty = totalCurrent
    statistics.availableQty = totalAvailable
    statistics.toInQty = totalPendingIn
    statistics.toOutQty = totalPendingOut
    
    // 更新表格数据
    inventoryList.value = mockInventoryDetails
    pagination.total = mockInventoryDetails.length
    
  } catch (error) {
    ElMessage.error('获取库存分布数据失败')
    console.error('获取库存分布数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 初始化产品信息
const initProductInfo = () => {
  if (route.query.itemId) {
    productInfo.itemId = route.query.itemId as string
    productInfo.itemName = route.query.itemName as string || ''
    productInfo.itemType = route.query.itemType as string || ''
    productInfo.itemSpec = route.query.itemSpec as string || ''
    productInfo.unitName = route.query.unitName as string || ''
  }
}

// 刷新数据
const refreshData = () => {
  fetchInventoryDistribution()
}

// 导出数据
const exportData = async () => {
  try {
    // 这里保留原有导出接口，如需更换请告知
    const res = await axios.post('/api/wcl/inventory/export-distribution', {
      itemId: productInfo.itemId
    }, { 
      responseType: 'blob' 
    })
    const url = window.URL.createObjectURL(new Blob([res.data]))
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', `${productInfo.itemName || '库存分布'}.xlsx`)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
    console.error('导出失败:', error)
  }
}

// 分页处理（如需分页可扩展）
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  fetchInventoryDistribution()
}

const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  fetchInventoryDistribution()
}

const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

// 页面加载时初始化
onMounted(() => {
  initProductInfo()
  fetchInventoryDistribution()
})
</script>

<style scoped>
.inventory-distribution {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 产品信息栏 */
.product-info-bar {
  background: white;
  padding: 15px 20px;
  margin-bottom: 20px;
  border-radius: 4px;
  display: flex;
  gap: 40px;
  align-items: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.product-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.product-name {
  font-weight: bold;
  color: #303133;
  font-size: 16px;
}

.label {
  color: #909399;
  font-size: 14px;
}

.value {
  color: #303133;
  font-size: 14px;
}

/* 统计卡片 */
.statistics-cards {
  margin-bottom: 20px;
}

.stat-card {
  border: 1px solid #e4e7ed;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.stat-content {
  text-align: center;
  padding: 20px 0;
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  margin-bottom: 8px;
}

.stat-number.blue {
  color: #409EFF;
}

.stat-number.orange {
  color: #E6A23C;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

/* 表格卡片 */
.table-card {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.table-actions {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

:deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #EBEEF5;
  background-color: #fafafa;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-table) {
  border: 1px solid #EBEEF5;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #606266;
  font-weight: bold;
}

:deep(.el-table td) {
  color: #606266;
}
</style> 